package cn.getech.data.metadata.controller.api;

import cn.getech.data.metadata.api.CollectionTableInfoApi;
import cn.getech.data.metadata.api.gateway.model.dto.OwnerRes;
import cn.getech.data.metadata.constant.YesOrNoEnum;
import cn.getech.data.metadata.controller.module.ModuleUtils;
import cn.getech.data.metadata.entity.CollectionSystemModuleEntity;
import cn.getech.data.metadata.mapper.CollectionSystemModuleMapper;
import cn.getech.data.metadata.mapper.CollectionTableMapper;
import cn.getech.data.metadata.service.CollectionSystemModuleService;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName BuildDataQualityReportController
 * @Description 元数据接口
 * @Author Getech
 * @Date 2021/2/5 10:40
 */

@RestController
@Slf4j
public class TableInfoFeignApiController implements CollectionTableInfoApi {

    @Autowired
    private CollectionSystemModuleService collectionSystemModuleService;

    @Autowired
    CollectionSystemModuleMapper collectionSystemModuleMapper;

    @Autowired
    CollectionTableMapper collectionTableMapper;

    @Override
    public String getAllPath(Integer moduleId) {
        List<CollectionSystemModuleEntity> moduleList = collectionSystemModuleService.list();
        String moduleName = ModuleUtils.getAllPath(moduleList, moduleId);
        return moduleName;
    }

    @Override
    public List<OwnerRes> getCollectionSystemTree(Integer tenantId) {
        List<CollectionSystemModuleEntity> list = collectionSystemModuleMapper.selectList(
                new QueryWrapper<CollectionSystemModuleEntity>()
                        .eq(tenantId != null, "tenant_id", tenantId)
                        .or()
                        .eq("sm_id",-1));
        List<OwnerRes> listTrees = Lists.newArrayList();
        List<OwnerRes> parentList=Lists.newArrayList();
        if (CollectionUtil.isNotEmpty(list)) {
            for (CollectionSystemModuleEntity moduleEntity : list) {
                OwnerRes owner = new OwnerRes(moduleEntity.getSmId(), moduleEntity.getSmName(), moduleEntity.getParentId());
                listTrees.add(owner);
                if (YesOrNoEnum.NO.getValue().equals(moduleEntity.getParentId())) {
                    parentList.add(owner);
                }
            }
            Map<Integer, List<OwnerRes>> sysListMap = listTrees.stream().filter(s -> !YesOrNoEnum.NO.getValue().equals(s.getParentId()))
                    .collect(Collectors.groupingBy(OwnerRes::getParentId));
            listTrees.forEach(s -> s.setChildren(sysListMap.get(s.getId())));
        }
        return parentList;
    }

}
